<?php
namespace app\admin\controller;
use app\admin\controller\Common;
use think\facade\Db;
use think\facade\View;
use think\Log;
use app\service\deviceService;
use app\service\wotuService;
class Device extends Common{
	public function devicelist()
	{
		
		//根据当前账号查询小区
        $com = $this->pidTokenId();
        //$whe['community_id'] = array('in',$com['community_id']);
        $whe=[];
        $whe[] =["community_id","in",$com['community_id']];
        $devicelist = (new deviceService())->deviceList($whe);
       
       	foreach ($devicelist as $key => $value) {
       		$value["state"]="";
			$value["onlineState"]="";
       		$res=(new wotuService())->deviceinquiry($value["devicekey"]);
			$rest=json_decode($res, true);
            //echo "<pre>";var_dump($rest);die;
			if($rest["code"]=="WO_SUS1000"){
				$value["state"]=$rest["data"]["state"];
				$value["onlineState"]=$rest["data"]["onlineState"];
			}else{
			   // echo "<pre>";var_dump($rest);die;
            }
			$list[] = $value;
       	}
       
        $number=(new deviceService())->devicecount($whe);
        View::assign('number',$number);
        if(!isset($list)){
            View::assign('devicelist',$devicelist);
        }else{
            View::assign('devicelist',$list);
        }
        View::assign('list',$devicelist);
        return View::fetch('device_list');
	}

	public function deviceadd(){
		if(request()->isPost()){
			$data=request()->post();
			//判断设备序列号是否重复        
            $deviceinfo = (new deviceService())->deviceinfo($data['devicekey']);
            if(!empty($deviceinfo)){
                $this->error('该设备已经已存在');
            }
            if($data["devicetype"]=="2"||$data["devicetype"]=="3"){
                if((empty($data["group"]))||(empty($data["building"]))||(empty($data["unit"]))){
                    $this->error("单元门组团楼栋单元不能为空");
                }
            }
            $communityinfo=Db::table("community")->where("id",$data["community_id"])->find();
            $data["community_name"]=$communityinfo["name"];
            //插入数据到数据库
            $result = (new deviceService())->deviceAdd($data);
            if($result){
                $this->success('门禁添加成功',url('deviceAdd'));
            }else{
                $this->error('门禁添加锁失败',url('deviceAdd'));
            }
		}else{
			$com = $this->pidTokenId();
            $whe['id'] = array('in',$com['community_id']);
	        $community = (new deviceService())->communityList($whe);
	        View::assign('community',$community);
			return View::fetch("device_add");
		}
	}
}